import re
import json
from apps.HttpTestcase.core.functions.fun_datatime import *
from apps.HttpTestcase.core.functions import *

# 全局参数
global_variable = re.compile(r'\{\$(\w+)?\}')
# 方法
param_variable = re.compile(r'\{\$(\w+\(.*?\))?\$}')

def matching(key, value):
    key = key if isinstance(key, str) else json.dumps(key, ensure_ascii=False)
    while global_variable.search(key):
        content = global_variable.search(key)
        replaced_key = global_variable.search(key).group(0)
        try:
            key = key.replace(replaced_key, value[global_variable.search(key).group(1)])
        except Exception as e:
            print("未找到待提取参数 {}".format(e))
            break
    return key


def param_matching_variables(content, variables):
    content = content if isinstance(content, str) else json.dumps(content)
    while global_variable.search(content):
        contents = global_variable.search(content)
        replaced_key = global_variable.search(content).group(0)
        try:
            content = content.replace(replaced_key, str(variables[global_variable.search(content).group(1)]))
        except Exception as e:
            print("未找到待提取参数 {}".format(e))
            break
    return content


def param_matching_functions(content):
    content = content if isinstance(content, str) else json.dumps(content)
    while param_variable.search(content):
        contents = param_variable.search(content)
        replaced_key = param_variable.search(content).group(0)
        fun = param_variable.search(content).group(1)
        replaced_value = eval(fun)
        try:
            content = content.replace(replaced_key, replaced_value)
        except Exception as e:
            print(e)
    return content
